from rest_framework.views import APIView
from rest_framework.response import Response
from host.models import Host
from .serializers import HostSerializer

# 获取主机视图
class HostView(APIView):
    def get(self, request):
        host_list = Host.objects.all()
        serializer_obj = HostSerializer(instance=host_list, many=True)
        return Response(serializer_obj.data)


from hippo_api.utils.handle_key import AppSetting
class CmdExecVIew(APIView):
    def post(self, request):
        print(request.data)
        # 获取批量的主机
        ids = request.data.get('ids')
        # 执行的批量命令
        cmd = request.data.get('cmd')
        if ids and cmd:
            # 获取所有主机model对象
            exec_host_list = Host.objects.filter(id__in=ids)
            pkey = AppSetting.get('private_key')  # 获取私钥
            response_list = []

            # 循环执行（应该用并发执行，之后优化代码再加）
            for host in exec_host_list:
                cli = host.get_ssh(pkey)  # get_ssh即models定义的get_ssh方法，返回sshcli连接
                res_code, res_data = cli.exec_command(cmd)

                # res_code为0表示ok，不为0说明指令执行有问题
                response_list.append({
                    'host_info': {
                        'id':host.id,
                        'hostname':host.hostname,
                        'ip_addr':host.ip_addr,
                        'port':host.port,
                    },
                    'res_code': res_code,
                    'res_data': res_data,
                })
            return Response(response_list)
        else:
            return Response({'error': '没有该主机或者没有输入指令'},status=400)


